<template>
  <div v-if="!auth.isLoggedIn" class="card-minimal p-6">
    <div class="text-white/70 mb-4">您还未登录，请先登录。</div>
    <router-link to="/login" class="btn-primary">去登录</router-link>
  </div>

  <div v-else class="grid md:grid-cols-3 gap-6">
    <!-- 左侧导航 -->
    <aside class="space-y-2">
      <button v-for="m in menus" :key="m.key" class="w-full text-left btn-outline" :class="page===m.key && 'btn-primary'" @click="page=m.key">{{ m.name }}</button>
    </aside>

    <!-- 右侧内容 -->
    <section class="md:col-span-2 space-y-6">
      <!-- 基本资料 -->
      <div v-if="page==='profile'" class="card-minimal p-6">
        <div class="text-white/60 text-sm mb-2">基本信息</div>
        <div>昵称：{{ auth.user?.name || '未设置' }}</div>
        <div>手机号：{{ auth.user?.phone || '未绑定' }}</div>
        <div class="mt-4"><button class="btn-outline" @click="auth.logout(); toast.info('已退出'); $router.push('/')">退出登录</button></div>
        <SubscriptionForm />
      </div>

      <!-- 其余区块保持不变 -->
      <!-- ... existing code ... -->

      <!-- 地址绑定 -->
      <div v-else-if="page==='address'" class="card-minimal p-6">
        <div class="flex items-center justify-between mb-4">
          <div class="text-white/60 text-sm">我的收货地址</div>
          <button class="btn-primary" @click="openAddr">新增地址</button>
        </div>
        <div v-if="(auth.addresses||[]).length===0" class="text-white/50 text-sm">暂无地址，请新增一个吧。</div>
        <ul v-else class="space-y-3">
          <li v-for="a in auth.addresses" :key="a.id" class="p-3 rounded-lg bg-white/5 ring-1 ring-white/10 flex items-center justify-between">
            <div>
              <div class="font-semibold">{{ a.name }} <span class="text-white/50 text-sm ml-2">{{ a.phone }}</span></div>
              <div class="text-white/60 text-sm mt-1">{{ a.address }}</div>
            </div>
            <div class="space-x-2">
              <button class="btn-outline" @click="editAddr(a)">编辑</button>
              <button class="btn-outline" @click="removeAddr(a.id)">删除</button>
            </div>
          </li>
        </ul>
        <dialog ref="addrDlg" class="modal">
          <form method="dialog" class="card-minimal p-6 w-[480px] space-y-3" @submit.prevent="saveAddr">
            <div class="text-white/80 font-semibold">地址信息</div>
            <input v-model.trim="addrForm.name" placeholder="收货人" class="input-control" />
            <input v-model.trim="addrForm.phone" placeholder="手机号" class="input-control" />
            <input v-model.trim="addrForm.region" placeholder="省市区/上级地址" class="input-control" />
            <input v-model.trim="addrForm.address" placeholder="详细地址" class="input-control" />
            <div class="flex justify-end gap-2 pt-2">
              <button type="button" class="btn-outline" @click="addrDlg?.close?.()">取消</button>
              <button type="submit" class="btn-primary">保存</button>
            </div>
          </form>
        </dialog>
      </div>

      <!-- 新增：订单查询 -->
      <div v-else-if="page==='orders'" class="space-y-4">
        <div class="card-minimal p-4">
          <div class="flex flex-wrap items-center gap-2">
            <input v-model.trim="ord.keyword" class="input-control w-full sm:w-80 md:w-96 max-w-md" placeholder="按订单号搜索" />
            <button class="btn-outline" @click="resetOrderSearch">重置</button>
            <button class="btn-primary" @click="loadOrders">查询</button>
          </div>
        </div>
        <div class="card-minimal p-0 overflow-hidden">
          <div class="divide-y divide-white/10">
            <div v-for="o in orders" :key="(o.orderId || o.orderNo || o.id)" class="p-4 flex items-center justify-between hover:bg-white/[0.03]">
              <div>
                <div class="font-medium">订单号：{{ o.orderId || o.orderNo || o.id }}</div>
                <div class="text-white/60 text-sm mt-1">金额：￥{{ o.totalPrice }}｜状态：{{ statusLabel(o.status) }}｜下单时间：{{ o.createTime }}</div>
              </div>
              <div class="flex items-center gap-2">
                <button class="btn-outline" @click="viewDetail(o)">详情</button>
              </div>
            </div>
            <div v-if="!loadingOrders && orders.length===0" class="p-8 text-center text-white/60">暂无订单</div>
          </div>
        </div>
        <div class="flex items-center justify-between">
          <div class="text-sm text-white/60">第 {{ ord.pageNum }} / {{ totalPages }} 页，共 {{ total }} 条</div>
          <div class="flex items-center gap-2">
            <button class="btn-outline" :disabled="ord.pageNum<=1" @click="toOrdPage(ord.pageNum-1)">上一页</button>
            <button class="btn-outline" :disabled="ord.pageNum>=totalPages" @click="toOrdPage(ord.pageNum+1)">下一页</button>
          </div>
        </div>
        <!-- 订单详情弹窗 -->
        <dialog ref="detailDlg" class="modal">
          <div class="card-minimal p-6 w-[720px] max-w-[95vw] space-y-4">
            <div class="flex items-center justify-between">
              <div class="text-white/80 font-semibold">订单详情</div>
              <button class="btn-outline" @click="detailDlg?.close?.()">关闭</button>
            </div>
            <div v-if="detailLoading" class="text-white/60">加载中...</div>
            <div v-else-if="!detail" class="text-white/60">暂无数据</div>
            <div v-else class="space-y-4">
              <div class="grid grid-cols-2 gap-2 text-sm text-white/70">
                <div>订单号：{{ detail.orderId || detail.orderNo || detail.order_id || detail.id }}</div>
                <div v-if="detail.status !== undefined">状态：{{ statusLabel(detail.status) }}</div>
                <div>金额：￥{{ detail.totalPrice ?? detail.amount ?? detail.totalAmount }}</div>
                <div>下单时间：{{ detail.createTime || detail.createdAt || detail.create_time }}</div>
                <div v-if="detail.paymentMethod">支付方式：{{ detail.paymentMethod }}</div>
              </div>
              <div class="rounded-lg ring-1 ring-white/10 overflow-hidden">
                <div class="p-3 text-white/70 text-sm bg-white/5">收货信息</div>
                <div class="p-4 text-sm text-white/80">
                  <div>收货人：{{ (shipping.receiverName) || '-' }}</div>
                  <div>手机号：{{ (shipping.phone) || '-' }}</div>
                  <div>地址：{{ ([shipping.address, shipping.detailAddress].filter(Boolean).join(' ')) || '-' }}</div>
                </div>
              </div>
              <div class="rounded-lg ring-1 ring-white/10 overflow-hidden">
                <div class="p-3 text-white/70 text-sm bg-white/5">商品明细</div>
                <div v-if="itemsList.length===0" class="p-6 text-white/60 text-sm">无商品明细</div>
                <div v-else class="divide-y divide-white/10">
                  <div v-for="(it,idx) in itemsList" :key="idx" class="p-3 flex items-center justify-between">
                    <div class="text-white/80">
                      <div class="font-medium">{{ it.name }}</div>
                      <div v-if="it.sku" class="text-xs text-white/50 mt-0.5">规格：{{ it.sku }}</div>
                    </div>
                    <div class="text-white/70 text-sm">￥{{ it.price }} × {{ it.qty }} = ￥{{ (Number(it.price)||0) * (Number(it.qty)||0) }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </dialog>
      </div>

    </section>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUnmount, onMounted, computed } from 'vue'
import { useAuthStore } from '../stores/auth'
import toast from '../composables/toast'
import SubscriptionForm from '@/components/SubscriptionForm.vue';
// 新增：用户地址 API
import { addUserAddress, findUserAddress, updateUserAddress, deleteUserAddress } from '@/api/UserAddressApi.js'
// 新增：订单查询 API（新增 fullDetail）
import { searchOrders, getOrderDetail, getFullOrderDetail } from '@/api/orderApi.js'

const auth = useAuthStore()

const menus = [
  { key: 'profile', name: '基本资料' },
  { key: 'address', name: '地址绑定' },
  { key: 'orders', name: '订单查询' },
  { key: 'cards', name: '银行卡绑定' },
  { key: 'bindings', name: '第三方账号绑定' },
  { key: 'security', name: '安全中心' },
  { key: 'logs', name: '登录日志' },
  { key: 'devices', name: '设备管理' },
  { key: 'forgot', name: '忘记密码' },
]


const page = ref('profile')

// 地址表单
const addrDlg = ref()
const addrForm = ref({ id: '', name: '', phone: '', region: '', address: '' })
function openAddr(){ addrForm.value = { id: '', name: '', phone: '', region: '', address: '' }; addrDlg.value?.showModal?.() }
function editAddr(a){
  // 从 _raw 中还原上级地址与详细地址
  addrForm.value = {
    id: a.id || '',
    name: a.name || '',
    phone: a.phone || '',
    region: (a._raw && (a._raw.address ?? '')) || '',
    address: (a._raw && (a._raw.detailAddress ?? '')) || (a.address || '')
  }
  addrDlg.value?.showModal?.()
}
// 新增：拉取用户地址列表并映射到前端所需字段
async function loadAddresses(){
  if(!auth.user?.id) return
  const resp = await findUserAddress(auth.user.id)
  const { code, data, msg } = resp?.data || {}
  if(code !== 200){ toast.error(msg || '获取地址失败'); return }
  // 将后端字段映射到前端使用的形态（兼容 Address 与 Useraddress 两种返回）
  auth.addresses = (data || []).map(it => ({
    id: it.addressId ?? it.id,
    name: it.reciver || it.receiverName || '',
    phone: it.phone || it.tel || it.receiverPhone || '',
    address: [it.address, it.detailAddress].filter(Boolean).join(' '),
    _raw: it
  }))
}
// 保存地址：有 id 走更新，无 id 走新增
async function saveAddr(){
  try{
    const payload = {
      addressId: addrForm.value.id || undefined,
      customerId: auth.user?.id,
      reciver: addrForm.value.name,
      phone: addrForm.value.phone,
      // 说明：address 为省市区等上级地址；detailAddress 为街道/门牌等详细地址
      address: addrForm.value.region,
      detailAddress: addrForm.value.address
    }
    const api = addrForm.value.id ? updateUserAddress : addUserAddress
    const resp = await api(payload)
    const { code, msg } = resp?.data || {}
    console.log(msg)
    if(code !== 200) throw new Error(msg || '保存失败')
    await loadAddresses()
    toast.success('已保存')
    addrDlg.value?.close?.()
  }catch(e){ toast.error(e.message || '保存失败') }
}
// 删除地址
async function removeAddr(id){
  try{
    const resp = await deleteUserAddress(id)
    const { code, msg } = resp?.data || {}
    if(code !== 200) throw new Error(msg || '删除失败')
    await loadAddresses()
    toast.success('已删除')
  }catch(e){ toast.error(e.message || '删除失败') }
}
// 首次进入或切换到地址页时自动拉取
onMounted(()=>{ if(auth.user?.id) loadAddresses() })
watch(()=>page.value, (p)=>{ if(p==='address' && auth.user?.id) loadAddresses(); if(p==='orders' && auth.user?.id) loadOrders() })
// 卡片表单
const cardDlg = ref()
const cardForm = ref({ bank: '', cardNo: '' })
function openCard(){ cardForm.value = { bank: '', cardNo: '' }; cardDlg.value?.showModal?.() }
function saveCard(){ try{ auth.addCard(cardForm.value); toast.success('已绑定'); cardDlg.value?.close?.() }catch(e){ toast.error(e.message) } }

// 安全中心
const pin = ref('')
function setPin(){ try{ auth.setPaymentPassword(pin.value); toast.success('已设置'); pin.value=''}catch(e){ toast.error(e.message) } }
function faceVerify(){ try{ auth.verifyFace(); toast.success('人脸验证通过（模拟）') }catch(e){ toast.error(e.message) } }
const oldPwd = ref('')
const newPwd = ref('')
function changePwd(){ try{ auth.changePassword(oldPwd.value, newPwd.value); toast.success('已修改'); oldPwd.value=''; newPwd.value='' }catch(e){ toast.error(e.message) } }

// 忘记密码
const fpPhone = ref('')
const fpCode = ref('')
const fpNew = ref('')
const fpCountdown = ref(0)
let timer
function clearTimer(){ if(timer){ clearInterval(timer); timer=null } }
function startCountdown(sec){ clearTimer(); fpCountdown.value = sec; if(sec>0){ timer = setInterval(()=>{ fpCountdown.value--; if(fpCountdown.value<=0){ clearTimer(); fpCountdown.value=0 } },1000) } }
function sendFPCode(){ try{ auth.sendSMS(fpPhone.value); startCountdown(60); toast.info('验证码已发送') }catch(e){ toast.error(e.message) } }
function doForgot(){ try{ auth.forgotPassword(fpPhone.value, fpCode.value, fpNew.value); toast.success('已重置'); page.value='profile' }catch(e){ toast.error(e.message) } }
function digitsOnly(field){
  if(field==='fpPhone') fpPhone.value = (fpPhone.value||'').replace(/\D+/g, '').slice(0,11)
  if(field==='fpCode') fpCode.value = (fpCode.value||'').replace(/\D+/g, '').slice(0,6)
}
watch(fpPhone, (val)=>{
  clearTimer()
  if(/^\d{11}$/.test(val)){
    const last = Number(localStorage.getItem('sms_last_'+val) || 0)
    const elapsed = Date.now() - last
    const remain = Math.ceil((60_000 - elapsed)/1000)
    if(remain>0 && remain<=60){ startCountdown(remain) } else { fpCountdown.value = 0 }
  } else { fpCountdown.value = 0 }
}, { immediate: false })
onBeforeUnmount(()=>{ clearTimer() })

// 订单查询：状态与分页
const ord = ref({ keyword: '', pageNum: 1, pageSize: 5 })
const orders = ref([])
const total = ref(0)
const loadingOrders = ref(false)
const totalPages = computed(()=> Math.max(1, Math.ceil(total.value / ord.value.pageSize)))

function statusLabel(s){
  const map = { 0: '待审批', 1: '待付款', 2: '已付款', 3: '已收货', 4: '已取消', 5: '已完成' }
  return map[s] || `状态${s}`
}

async function loadOrders(){
  if(!auth.user?.id){ toast.error('请先登录'); return }
  loadingOrders.value = true
  try{
    const payload = {
      orderId: ord.value.keyword || undefined,
      customerId: auth.user.id,
      pageNum: ord.value.pageNum,
      pageSize: ord.value.pageSize
    }
    const resp = await searchOrders(payload)
    const { code, data, msg } = resp?.data || {}
    if(code !== 200){ throw new Error(msg || '查询失败') }
    // data 是 PageInfo<Order>
    orders.value = Array.isArray(data?.list) ? data.list : []
    total.value = Number(data?.total || 0)
  }catch(e){ toast.error(e.message || '查询失败') }
  finally{ loadingOrders.value = false }
}
function toOrdPage(p){ ord.value.pageNum = Math.max(1, Math.min(totalPages.value, p)); loadOrders() }
function resetOrderSearch(){ ord.value = { keyword: '', pageNum: 1, pageSize: 5 }; loadOrders() }

// 订单详情：数据与弹窗
const detailDlg = ref()
const detail = ref(null)
const detailLoading = ref(false)
// 对订单详情中的收货信息做兼容映射（支持多种后端返回形态）
const shipping = computed(()=>{
  const d = detail.value || {}
  const base = (d.order) || d // 新接口将主单放在 d.order
  const addrObj = base.shippingAddress || base.addressInfo || base.addr || base.addressObj || base.addressDTO || base.address
  const recvObj = base.receiver || base.consignee || base.user || base.customer
  const receiverName = base.receiverName || base.reciver || recvObj?.name || recvObj?.realName || ''
  const phone = base.receiverPhone || base.phone || base.tel || recvObj?.phone || recvObj?.mobile || ''
  // 解析地址字段，兼容字符串/对象/数组
  const parseAddress = (addr)=>{
    if(!addr) return ''
    if(typeof addr === 'string') return addr
    if(Array.isArray(addr)) return addr.filter(Boolean).join(' ')
    if(typeof addr === 'object'){
      const parts = [addr.address, addr.region, addr.province, addr.city, addr.district, addr.area, addr.county, addr.town, addr.street]
      const s = parts.filter(Boolean).join(' ')
      return s || ''
    }
    return ''
  }
  const region = parseAddress(base.address) || parseAddress(addrObj)
  const detailAddress = base.detailAddress || addrObj?.detailAddress || addrObj?.detail || ''
  return { receiverName, phone, address: region, detailAddress }
})
const itemsList = computed(()=>{
  const d = detail.value || {}
  let list = d.items || d.orderItems || d.details || d.orderItemList || d.orderDetailList || []
  // 新接口将明细列表放在 d.orderItems
  if(Array.isArray(d.orderItems)) list = d.orderItems
  if(Array.isArray(d)) list = d
  if(!Array.isArray(list)) list = []
  return list.map(x => ({
    name: x.productName || x.name || x.title || `商品${x.productId || x.id || ''}`,
    price: (x.price ?? x.unitPrice ?? x.amount ?? 0),
    qty: (x.buyNum ?? x.quantity ?? x.qty ?? x.count ?? 1),
    sku: x.sku || x.spec || x.attr || ''
  }))
})

async function viewDetail(o){
  try{
    detailLoading.value = true
    detail.value = null
    const oid = o.orderId ?? o.id ?? o.orderNo
    if(!oid){ throw new Error('订单号缺失') }

    // 优先使用新的组合接口
    let resp = await getFullOrderDetail(oid)
    let { code, data, msg } = resp?.data || {}

    // 回退到老接口（仅有明细）
    if(code !== 200){
      resp = await getOrderDetail(oid)
      const res2 = resp?.data || {}
      code = res2.code; data = res2.data; msg = res2.msg
    }

    if(code !== 200){ throw new Error(msg || '获取详情失败') }

    // 规范化：新接口 data = { order: {...}, orderItems: [...] }
    const normalize = (src)=>{
      if(!src) return null
      // 场景C：新接口，包含 order 和 orderItems
      if(src.order && Array.isArray(src.orderItems)){
        const o = { ...(src.order || {}) }
        o.items = src.orderItems
        // 兼容：若没有 totalPrice，按明细计算
        if(o.totalPrice == null){
          o.totalPrice = src.orderItems.reduce((sum, x)=>{
            const p = Number(x.price ?? x.unitPrice ?? x.amount ?? 0)
            const q = Number(x.buyNum ?? x.quantity ?? x.qty ?? x.count ?? 1)
            return sum + p * q
          }, 0)
        }
        return o
      }
      // 场景A：data 为明细数组
      if(Array.isArray(src)){
        const list = src
        const first = list[0] || {}
        const totalPrice = list.reduce((sum, x) => {
          const p = Number(x.price ?? x.unitPrice ?? x.amount ?? 0)
          const q = Number(x.buyNum ?? x.quantity ?? x.qty ?? x.count ?? 1)
          return sum + p * q
        }, 0)
        return {
          orderId: first.orderId ?? first.orderNo ?? first.order_id ?? first.id,
          createTime: first.createTime || first.createdAt || first.create_time || first.orderTime,
          totalPrice,
          items: list
        }
      }
      const d = src || {}
      if(d.order || d.orderInfo){
        const o = d.order || d.orderInfo
        // 合并明细列表
        o.items = o.items || d.items || d.orderItems || d.details || d.orderItemList || d.orderDetailList || []
        // 透传可能存在的地址/收件人对象
        if(!o.address && d.address) o.address = d.address.address || d.address.region || d.address
        if(!o.detailAddress && d.address) o.detailAddress = d.address.detailAddress || d.address.detail || ''
        if(!o.receiverName && d.receiver) o.receiverName = d.receiver.name || d.receiver.realName || ''
        if(!o.phone && d.receiver) o.phone = d.receiver.phone || d.receiver.mobile || d.receiver.tel || ''
        return o
      }
      return d
    }

    console.debug('[order-detail] raw data:', data)
    detail.value = normalize(data)
    detailDlg.value?.showModal?.()
  }catch(e){ toast.error(e.message || '获取详情失败') }
  finally{ detailLoading.value = false }
}
</script>